<template>
  <div>
    <el-form ref="form" :model="spu" label-width="80px" style="width: 800px">
      <el-form-item label="Spu名称">
        <el-input placeholder="请输入Spu名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spu.tmId" placeholder="请选择品牌">
          <el-option
            v-for="tm in tradeMarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="描述"
          rows="4"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handleAvatarSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="saleAttr"
          :placeholder="`还有${unSelectSaleAttr.length}种属性未选择`"
        >
          <el-option
            v-for="unSelect in unSelectSaleAttr"
            :label="unSelect.name"
            :value="unSelect"
            :key="unSelect.id"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!saleAttr"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table
          style="width: 100%; margin-top: 20px"
          border
          :data="spu.spuSaleAttrList"
        >
          <el-table-column
            label="序号"
            width="82"
            align="center"
            type="index"
          ></el-table-column>
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="82"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="true"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="82">
            <template slot-scope="{ $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSpuInfo">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      spu: {
        //三级分类的id
        category3Id: 0,
        //描述
        description: "",
        //spu名称
        spuName: "",
        //品牌的id
        tmId: "",
        //收集SPU图片的信息
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        //平台属性与属性值收集
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   saleAttrName: "string",
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      },
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //存储Spu图片的数据
      saleAttrList: [], //销售属性的数据
      //收集新增的属性名和属性id，还有属性值列表
      saleAttr: "",
    };
  },
  methods: {
    //初始化编辑spu数据
    async initSpuData(spu) {
      let spuResult = await this.$API.spu.reqSpu(spu.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      let tmResult = await this.$API.spu.reqTmList();
      if (tmResult.code == 200) {
        this.tradeMarkList = tmResult.data;
      }
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
      if (spuImageResult.code == 200) {
        let imgList = spuImageResult.data;
        // 照片墙必须要有name和url字段
        imgList.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = imgList;
      }

      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    // 初始化编辑spu数据
    async addSpuData(category3Id) {
      this.spu.category3Id = category3Id;
      let tmResult = await this.$API.spu.reqTmList();
      if (tmResult.code == 200) {
        this.tradeMarkList = tmResult.data;
      }
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    //删除图片
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },
    //放大图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功
    handleAvatarSuccess(response, file, fileList) {
      this.spuImageList = fileList;
    },
    //取消展示spu列表数据
    cancel() {
      this.$emit("changeScene", 0);
      Object.assign(this._data, this.$options.data());
    },
    //给spu添加销售属性
    addSaleAttr() {
      let baseSaleAttrId = this.saleAttr.id;
      let saleAttrName = this.saleAttr.name;
      // 整理参数
      let newSaleAttrList = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spu.spuSaleAttrList.push(newSaleAttrList);
      this.saleAttr = "";
    },
    //点击添加显示input
    showInput(row) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //输入框失去焦点显示button，将数据整理添加到spuSaleAttrValueList
    handleInputConfirm(row) {
      row.inputVisible = false;
      if (row.inputValue.trim() == "") {
        this.$message({ type: "error", message: "输入不能为空" });
        return;
      }
      let result = row.spuSaleAttrValueList.some((item) => {
        return row.inputValue == item.saleAttrValueName;
      });
      if (result) {
        this.$message({ type: "error", message: "属性值不能重复" });
        return;
      }
      const spuSaleAttrValue = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue,
      };
      row.spuSaleAttrValueList.push(spuSaleAttrValue);
    },
    //保存数据
    async saveSpuInfo() {
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url,
        };
      });
      let result = await this.$API.spu.reqSaveSpu(this.spu);
      if (result.code == 200) {
        this.$emit("changeScene", 0);
        this.$message({
          type: "success",
          message: "保存成功",
        });
      }
      Object.assign(this._data, this.$options.data());
    },
  },
  computed: {
    //未选择的销售属性
    unSelectSaleAttr() {
      return this.saleAttrList.filter((item) => {
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>